package com.gjt.clientSocket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

/**
 * Created with Intel IDEA.
 *
 * @Auther: gjt
 * @Date: 2024/5/4 16:32
 */
public class WhoisGUI extends JFrame {
    private JTextField searchString = new JTextField(30);
    private JTextArea names = new JTextArea(15 ,18);
    private JButton findButton =  new JButton("Find");
    private ButtonGroup searchIn = new ButtonGroup();
    private ButtonGroup searchFor = new ButtonGroup();
    private JCheckBox exactMatch = new JCheckBox("Exact Match", true);
    private JTextField chosenServer = new JTextField();
    private WhoIs server;
    public WhoisGUI(WhoIs whoIs){
        super("Whois");
        this.server = whoIs;
        Container pane = this.getContentPane();

        Font f = new Font("Monospaced", Font.PLAIN, 12);
        // 给名字域添加字体
        names.setFont(f);
        // 不可修改
        names.setEditable(false);

        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new GridLayout(1,1,10,10));
        JScrollPane jsp = new JScrollPane(names);
        centerPanel.add( jsp);
        pane.add("Center", centerPanel);



        JPanel northPanelTop = new JPanel();
        northPanelTop.setLayout(new FlowLayout(FlowLayout.LEFT));
        northPanelTop.add(new JLabel("Whois: "));
        northPanelTop.add("North", searchString);
        northPanelTop.add(exactMatch);
        northPanelTop.add(findButton);

        JPanel northPanel = new JPanel();
        northPanel.setLayout(new BorderLayout(2,1));
        northPanel.add("North", northPanelTop);

        JPanel northPanelBottom = new JPanel();
        northPanelBottom.setLayout(new GridLayout(1,3,5,5));
        northPanelBottom.add(initRecordType());
        northPanelBottom.add(initSearchFields());
        northPanelBottom.add(initServerChoice());

        northPanel.add("Center",northPanelBottom);
        pane.add("North",northPanel);

        ActionListener al = new LookupNames();
        findButton.addActionListener(al);
        searchString.addActionListener(al);
    }
    private JPanel initRecordType(){
        JPanel p =new JPanel();
        p.setLayout(new GridLayout(6,2,5,2));
        p.add(new JLabel("Search for: "));
        p.add(new JLabel(""));
        JRadioButton any = new JRadioButton("Any", true);
        any.setActionCommand("Any");
        searchFor.add(any);
        p.add(any);

        p.add(this.makeRadioButton("Network"));
        p.add(this.makeRadioButton("Person"));
        p.add(this.makeRadioButton("Host"));
        p.add(this.makeRadioButton("Domain"));
        p.add(this.makeRadioButton("Organization"));
        p.add(this.makeRadioButton("Group"));
        p.add(this.makeRadioButton("Gateway"));
        p.add(this.makeRadioButton("ASN"));

        return p;
    }

    private JRadioButton makeRadioButton (String label){
        JRadioButton button = new JRadioButton(label, false);
        button.setActionCommand(label);
        searchFor.add(button);
        return button;
    }

    private JPanel initSearchFields(){

        JPanel p = new JPanel();
        p.setLayout(new GridLayout(6,1,5,2));
        p.add(new JLabel("Search In: "));

        JRadioButton all = new JRadioButton("All" , true);
        all.setActionCommand("All");
        searchIn.add(all);
        p.add(all);

        p.add(this.makeSearchInRadioButton("Name"));
        p.add(this.makeSearchInRadioButton("Mailbox"));
        p.add(this.makeSearchInRadioButton("Handle"));

        return p;
    }

    private JRadioButton makeSearchInRadioButton(String label){
        JRadioButton button = new JRadioButton(label, false);
        button.setActionCommand(label);
        searchFor.add(button);
        return button;
    }

    private JPanel initServerChoice(){
        final JPanel p =new JPanel();
        p.setLayout(new GridLayout(6,1,5,2));
        p.add(new JLabel("Search At: "));

        chosenServer.setText(server.getHost().getHostName());
        p.add(chosenServer);

        chosenServer.addActionListener(e -> {
            try{
                server = new WhoIs(chosenServer.getText());
            }catch (UnknownHostException ex){
                JOptionPane.showMessageDialog(p,ex.getMessage(),"Alert",JOptionPane.ERROR_MESSAGE);
            }
        });
        return  p;
    }

    private class LookupNames implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            names.setText("");
            SwingWorker<String, Object> worker = new Lookup();
            // 建立网络连接
            worker.execute();
        }
    }

    private class Lookup extends SwingWorker<String,Object>{

        /**
         * 完成长时间运行的有大量i/o的操作。 他不与GUI交互
         */
        @Override
        protected String doInBackground() throws Exception {
            WhoIs.SearchIn group = WhoIs.SearchIn.ALL;
            WhoIs.SearchFor category = WhoIs.SearchFor.ANY;

            String searchForLabel = searchFor.getSelection().getActionCommand();
            String searchInLabel = searchIn.getSelection().getActionCommand();

            switch (searchInLabel) {
                case "Name":
                    group = WhoIs.SearchIn.NAME;
                    break;
                case "Mailbox":
                    group = WhoIs.SearchIn.MAILBOX;
                    break;
                case "Handle":
                    group = WhoIs.SearchIn.HANDLE;
                    break;
            }

            switch (searchForLabel) {
                case "Network":
                    category = WhoIs.SearchFor.NETWORK;
                    break;
                case "Person":
                    category = WhoIs.SearchFor.PERSON;
                    break;
                case "Host":
                    category = WhoIs.SearchFor.HOST;
                    break;
                case "Domain":
                    category = WhoIs.SearchFor.DOMAIN;
                    break;
                case "Organization":
                    category = WhoIs.SearchFor.ORGANIZATION;
                    break;
                case "Group":
                    category = WhoIs.SearchFor.GROUP;
                    break;
                case "Gateway":
                    category = WhoIs.SearchFor.GATEWAY;
                    break;
                case "ASN":
                    category = WhoIs.SearchFor.ASN;
                    break;
            }

            server.setHost(chosenServer.getText());
            return server.lookUpNames(searchString.getText(),category,group,exactMatch.isSelected());
        }

        /**
         * 这个方法会在doInBackgroud() 后由时间分发线程自动调用，它可以更新GUi , 调用get() 方法获取doInBackground（） 计算的返回值
         */
        @Override
        protected void done() {
            try{
                names.setText(get());
            }catch (Exception e){
                JOptionPane.showMessageDialog(WhoisGUI.this,e.getMessage(),"Lookup Failed",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public static void main(String[] args) {
        try{
            WhoIs server = new WhoIs();
            WhoisGUI a = new WhoisGUI(server);
            a.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            a.pack();
            EventQueue.invokeLater(new FrameShower(a));
        }catch (UnknownHostException e){
            e.printStackTrace();
        }

    }


    private static class FrameShower implements Runnable{
        private final Frame frame;
        FrameShower(Frame frame){
            this.frame = frame;
        }

        @Override
        public void run() {
            // 显示窗口
            frame.setVisible(true);
        }
    }
}

